package huaweiod.first;

import java.util.*;

/**
 * 华为OD机试真题 Java 实现【端口合并】【2022.11 Q4 新题】
 */
public class A_2023_27_PortMerge {

    public static void main(String[] args) {
        // 输入处理
        Scanner in = new Scanner(System.in);
        int m = Integer.parseInt(in.nextLine());

        // 限定范围
        if (m > 10 || m < 1) {
            System.out.println("[[]]");
            return;
        }

        ArrayList<ArrayList<Integer>> ranges = new ArrayList<>();

        for (int i = 0; i < m; i++) {
            Integer[] temp_arr = Arrays.stream(in.nextLine().split(",")).map(Integer::parseInt).toArray(Integer[]::new);
            // 限定范围
            if (temp_arr.length < 1 || temp_arr.length > 100) {
                System.out.println("[[]]");
                return;
            }

            ArrayList<Integer> temp_arrList = new ArrayList<>(Arrays.asList(temp_arr));
            ranges.add(temp_arrList);
        }

        // process
        while (merge(ranges)) {

        }

        List<TreeSet<Integer>> result = new ArrayList<>();
        for (int i = 0; i < ranges.size(); i++) {
            TreeSet<Integer> treeSet = new TreeSet<>(ranges.get(i));
            result.add(treeSet);
        }
        // 打印
        StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
        for (int i = 0; i < result.size(); i++) {
            TreeSet<Integer> treeSet = result.get(i);
            StringJoiner innerStringJoiner = new StringJoiner(",", "[", "]");
            for (Integer ele : treeSet) {
                innerStringJoiner.add(String.valueOf(ele));
            }
            stringJoiner.add(innerStringJoiner.toString());
        }
        System.out.println(stringJoiner.toString());
    }

    public static boolean merge(ArrayList<ArrayList<Integer>> ranges) {
        for (int i = ranges.size() - 1; i >= 0; i--) {
            for (int j = i - 1; j >= 0; j--) {
                TreeSet<Integer> set1 = new TreeSet<>(ranges.get(i));
                TreeSet<Integer> set2 = new TreeSet<>(ranges.get(j));
                if (check(set1, set2)) {
                    ranges.get(j).addAll(ranges.get(i));
                    ranges.remove(i);
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean check(TreeSet<Integer> set1, TreeSet<Integer> set2) {
        int ans = 0;
        for (Integer s1 : set1) {
            if (set2.contains(s1)) {
                ans++;
                if (ans == 2) {
                    return true;
                }
            }
        }
        return false;
    }
}